#!/bin/bash
#
# Automatic Network Configuration Tool - auto-netconf
#
# Written by Lajos Koszti [Ajnasz] (2006-2007)
#
#   * http://ajnasz.hu
#   * ajnasz@ajnasz.hu
#   * ajnasz@gmail.com
#
# Project Homepage
#
#   * http://code.google.com/p/auto-netconf
#
# Licence
#
#   * GNU GENERAL PUBLIC LICENSE Version 2
#   * http://www.gnu.org/licenses/gpl.txt


########################## Configuration START ##########################
SECESSIDS=( [0]="Ajnasz" ); # known crypted networks ssid-s: ( [0]="Foonet" [1]="Bar net" );
ESSIDS=(); # known uncrypted networks ssid-s: ( [0]="Foonet" [1]="Bar net" );
PRIMARY='sec'; # type of preferred network: 'sec' or '', the sec is secure
WIFIMODULE="ipw2200"; # wifi card module name: ipw2200 etc.
WPADRIVER="wext"; # wpa_supplicant drivername: wext, ipw, madwifi etc.
WIFIIFACE="eth1"; # wireless interface
WIREDIFACE="eth0"; #  wired interface

FW="/etc/init.d/firewall"; # your firewall (iptables) script path

# change these variables if need
IFCFG="/sbin/ifconfig";
IWCFG="/sbin/iwconfig";
IWLIST="/sbin/iwlist";
WPASUP="/sbin/wpa_supplicant";
WPACONF="/etc/wpa_supplicant/wpa_supplicant.conf";
IFDOWN="/sbin/ifdown";
IFUP="/sbin/ifup";
ROUTE="/sbin/route";
RMMOD="/sbin/rmmod";
MODPROBE="/sbin/modprobe";
KILLALL="/usr/bin/killall";
ETHTOOL="/usr/sbin/ethtool"; # package ethtool
MIITOOL="/sbin/mii-tool";  # package net-tools - out of usage, the ethtool preferred
########################## Configuration END ##########################

SECESSIDSLENGTH=${#SECESSIDS[@]}; # count of the secured network ssids
ESSIDSLENGTH=${#ESSIDS[@]}; # count of the unsecured network ssids
ESSID=""; # initial variable
SECESSID=""; # initial variable

# returns the ip of the specified interfacee
function getIp {
  IP=`$IFCFG $1 | grep inet | awk '{ print $2 }' | cut -d":" -f2`;
  echo $IP;
}

# returns the available essids
function getESSID {
  S=`$IWLIST $WIFIIFACE scanning | grep ESSID | sed -n 's/ESSID:"\(.*\)"/\1/g p' | awk '{ printf $1 }'`;
  echo $S;
}

# return the the network's ssid or empty
function getWifiNets {
  echo `getESSID | grep $1`;
}

# start, stop the firewall
function fw {
  if [ "$FW" != "" ]; then
    case "$1" in
      "stop")
        $FW stop;
      ;;
      "start")
        $FW start;
      ;;
    esac
  fi
}

# reload the wireless card module
function reloadWifiModule {
  # unload the wireless module
  echo -ne "\E[1;33m$RMMOD\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
  echo -n " $WIFIMODULE";
  $RMMOD $WIFIMODULE &>/dev/null;
  echo -e " . \E[1;37mdone\033[0m";
  # load the wireless module
  echo -ne "\E[1;33m$MODPROBE\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
  echo -n " $WIFIMODULE";
  $MODPROBE $WIFIMODULE &>/dev/null;
  echo -e " . \E[1;37mdone\033[0m";
}

# check for predefined wireless networks
function checkWifiNets {
  # Search for uncrypted networks
  index=0;
  net=""; # network name init variable
  availNets=`getESSID`;
  while [ "$index" -lt "$ESSIDSLENGTH" ]; do
    net=`getWifiNets ${ESSIDS[$index]}`;
    if [ ! -z "$net" ]; then
      ESSID="${ESSIDS[$index]}";
    fi
    index+=1;
  done
  # Search for crypted networks
  index=0;
  while [ "$index" -lt "$SECESSIDSLENGTH" ]; do
    net=`getWifiNets ${SECESSIDS[$index]}`;
    if [ -z "$net" ]; then
      index+=1;
    else
      SECESSID="${SECESSIDS[$index]}";
      index+=1;
    fi
  done
  # if network not found
  if [ -z "$ESSID" ] && [ -z "$SECESSID" ]; then
    echo -e "\E[1;31mI can't find any essid from the list\033[0m";
    echo -e "Available networks:";
    echo -e "\E[1;32m$availNets\033[0m";
    echo "";
    exit 1;
  else
    echo -e "\E[1mOK, I found \E[1;32m$SECESSID $ESSID\E[0m\E[1m network!\033[0m";
  fi
}

function down {
  if [ $# -gt 0 ]; then

    echo -ne "\E[1;33m$IFCFG\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
    echo -ne " \E[1;36m$1 \E[1;34mdown\033[0m";
    $IFCFG $1 down &>/dev/null;
    echo -ee " . \E[1;37mdone\033[0m";

    echo -ne "\E[1;33m$IFDOWN\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
    echo -ne " \E[1;36m$1\033[0m";
    $IFDOWN $1 &>/dev/null;
    echo -e " . \E[1;37mdone\033[0m";

  fi;
}

function showIPS {
  WFip=`getIp $WIFIIFACE`;
  WRip=`getIp $WIREDIFACE`;
  if [ ! -z "$WFip" ]; then
    echo -e "\E[1;36m$WIFIIFACE\033[0m ip: \E[1;34m$WFip\033[0m";
  fi
  if [ ! -z "$WRip" ]; then
    echo -e "\E[1;36m$WIREDIFACE\033[0m ip: \E[1;34m$WRip\033[0m";
  fi
}

# configure the wifi interface
function upWIFI {
  down $WIREDIFACE;
  down $WIFIIFACE;
  ISLOADEDWIFI=`lsmod | awk '{ printf $1 }' | grep $WIFIMODULE`; # the wifimoudle is loaded
  if [ ! -z "$ISLOADEDWIFI" ]; then
    # if the wifi module is loaded, reload it
    reloadWifiModule;
  fi
    # kill wpa_supplicant
  echo -ne "\E[1;33m$KILLALL\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
  echo -n " wpa_supplicant";
  $KILLALL wpa_supplicant &>/dev/null;
  echo -e " . \E[1;37mdone\033[0m";
  # configure network card
  if [ "$PRIMARY" != "sec" ]; then
    # if no uncrypted net
    if [ -z "$ESSID" ]; then
      # iwconfig wireless interface
      echo -ne "\E[1;33m$IWCFG\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
      echo -ne " \E[1;36m$WIFIIFACE\033[0m essid \E[1;32m$SECESSID\033[0m";
      $IWCFG $WIFIIFACE essid $SECESSID &>/dev/null;
      echo -e " . \E[1;37mdone\033[0m";
      # start wpa_supplicant
      echo -ne "\E[1;33m$WPASUP\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
      echo -n " -B -D $WPADRIVER -i $WIFIIFACE -c $WPACONF";
      $WPASUP -B -D $WPADRIVER -i $WIFIIFACE -c $WPACONF &>/dev/null;
      echo -e " . \E[1;37mdone\033[0m";
    else
      # iwconfig wireless interface with uncrypted network
      echo -ne "\E[1;33m$IWCFG\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
      echo -ne " \E[1;36m$WIFIIFACE\033[0m essid \E[1;32m$ESSID\033[0m";
      $IWCFG $WIFIIFACE essid $ESSID &>/dev/null;
      echo -e " . \E[1;37mdone\033[0m";
    fi
  else
    # if no crypted network
    if [ -z "$SECESSID" ]; then
      # iwconfig wireless interface
      echo -ne "\E[1;33m$IWCFG\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
      echo -ne " \E[1;36m$WIFIIFACE\033[0m essid \E[1;32m$ESSID\033[0m";
      $IWCFG $WIFIIFACE essid $ESSID &>/dev/null;
      echo -e " . \E[1;37mdone\033[0m";
    else
      # iwconfig wireless interface
      echo -ne "\E[1;33m$IWCFG\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
      echo -ne " \E[1;36m$WIFIIFACE\033[0m essid \E[1;32m$SECESSID\033[0m";
      $IWCFG $WIFIIFACE essid $SECESSID &>/dev/null;
      echo -e " . \E[1;37mdone\033[0m";
      # start wpa_supplicant
      echo -ne "\E[1;33m$WPASUP\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
      echo -n " -B -D $WPADRIVER -i $WIFIIFACE -c $WPACONF";
      $WPASUP -B -D wext -i $WIFIIFACE -c $WPACONF &>/dev/null;
      echo -e " . \E[1;37mdone\033[0m";
    fi
  fi
  # ifup wireless interface
  echo -ne "\E[1;33m$IFUP\033[0m $WIFIIFACE" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
  echo -ne " \E[1;36m$WIFIIFACE\033[0m";
  $IFUP $WIFIIFACE &>/dev/null;
  echo -e " . \E[1;37mdone\033[0m";
  # display the wireless interface ip address
#  ip=`getIp $WIFIIFACE`;
#  echo -e "\E[1m$WIFIIFACE\E[0m ip: \E[1;34m$ip\033[0m";
}
# static configuration for the wired interface
function upEth0Home {
  # $IFDOWN $WIFIIFACE &>/dev/null;
  down $WIFIIFACE;
  # configure wired interface
  echo -ne "ifconfig \E[1;36m$WIREDIFACE\033[0m 10.1.0.2 netmask 255.255.255.0";
  $IFCFG $WIREDIFACE 10.1.0.2 netmask 255.255.255.0;
  echo -e " . \E[1;37mdone\033[0m."
  # configure route table
  echo -n "$ROUTE add default gw 10.1.0.1";
  $ROUTE add default gw 10.1.0.1 2>/dev/null;
  echo -e " . \E[1;37mdone\033[0m."
  # set up nameserver
  echo -n "echo "nameserver 10.1.0.1" > /etc/resolv.conf";
  echo "nameserver 10.1.0.1" > /etc/resolv.conf;
  echo -e " . \E[1;37mdone\033[0m."
}
# gets the iface status with mii-tool
function checkETHMIItool {
  if [ $MIITOOL $WIREDIFACE | grep -q "no link" ]; then
    s=1;
  else
    s=0;
  fi
  return $s;
}
# check the configuration
function checkConf {
  ERROR=0;
  # wifimodule not configured, fatal error
  if [ -z "$WIFIMODULE" ]; then
    ERROR+=1;
    echo -e "\E[1;31mWIFIMODULE variable is empty!\033[0m";
  fi
  # wpa_supplicant dirver not configured, fatal error
  if [ -z "$WPADRIVER" ]; then
    ERROR+=2;
    echo -e "\E[1;31mWPADRIVER variable is empty!\033[0m";
  fi
  # firewall not configured
  if [ -z "$FW" ]; then
    echo -e "\E[1;31mThe FW (firewall) variable isn't configured!\033[0m";
  fi
  # if fatal found error, exit
  if [ $ERROR -gt 0 ];then
    exit $ERROR;
  fi;
}
#get the status of the wireless interface
function wirelessStatus {
  echo `$ETHTOOL $WIFIIFACE | grep "Link detected" | awk '{ printf $3 }'`; # get the iface status with ethtool
}
#get the status of the wired interface
function wiredStatus {
  echo `$ETHTOOL $WIREDIFACE | grep "Link detected" | awk '{ printf $3 }'`; # get the iface status with ethtool
}
##################################################################
# check configuration
##################################################################
checkConf;
##################################################################
# if argument
WIREDSTATUS=`wiredStatus`;
WIRELESSSTATUS=`wirelessStatus`;
if [ $# -gt 0 ]; then
  # if there is any argument, first get the $WIREDIFACE status
  case "$1" in
    # if the argument is start or restart, check the $WIREDIFACE status
    "start" | "restart" | "force" | "-f")
      # if wired link is up, let's start it
      if [ "$WIREDSTATUS" == "yes" ]; then
        fw stop;
        down $WIREDIFACE;
        down $WIFIIFACE;
        echo -ne "\E[1;33m$IFUP\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
        echo -ne " \E[1;36m$WIREDIFACE\033m";
        $IFUP $WIREDIFACE &>/dev/null;
        echo -e " . \E[1;37mdone\033[0m";
        showIPS;
        fw start;
        exit 0;
      # else, try to set up the wireless interface
      else
        checkWifiNets;
        fw stop;
        upWIFI;
        showIPS;
        fw start;
        exit 0;
      fi
    ;;
    # if the argument is stop, ifdown the interfaces
    "stop")
      IP0=`getIp "$WIREDIFACE"`;
      IP1=`getIp "$WIFIIFACE"`;
      if [ "$WIREDSTATUS" == "yes" ]; then
        down $WIREDIFACE;
      fi
      if [ "$WIRELESSSTATUS" == "yes" ]; then
        echo -ne "\E[1;33m$KILLALL\033[0m" | awk '{ sub(/(\/[a-z\/]+\/)/, ""); printf $1 }';
        $KILLALL wpa_supplicant &>/dev/null;
        echo -e " . \E[1;37mdone\033[0m";
        down $WIFIIFACE;
      fi
      fw stop;
      exit 0;
    ;;
    *)
      echo "Bad argument, use: start, restart, stop, force, -f";
      exit 1;
  esac;
# if no argument
else
  # get the interfaces ip
  IP0=`getIp "$WIREDIFACE"`; # ip of the wired interface
  IP1=`getIp "$WIFIIFACE"`; # ip of the wireless interface
  # if the wired interface link is down and the wifi isn't have ip, configure it
  if [ $WIREDSTATUS == "no" ] && [ "$WIRELESSSTATUS" == "no" ]; then
    checkWifiNets;
    fw stop;
    upWIFI;
    showIPS;
    fw start;
    exit 0;
  # if the wifi iface have ip, just display
  elif [ -n "$IP1" ]; then
    echo $IP1;
    exit 0;
  # if the wired interface have ip, just display
  elif [ -n "$IP0" ]; then
    echo $IP0;
    exit 0;
  # configure the wired interface
  elif [ "$WIREDSTATUS" == "yes" ]; then
    fw stop;
    upEth0Home;
    fw start;
    exit 0;
  else
    exit 1;
  fi
fi
